package kocla.com.myapplication;

/**
 * 作者：池锦标 on 2016/9/23 15:10
 * 邮箱：292284583@qq.com
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Log;

/**
 * @author 杨贵松
 * @version V1.0
 * @project: TIIS
 * @Title: SimpleClient.java
 * @Package com.rainet.tiis.network
 * @Description: HTTP请求factory
 * @date 2014-3-18 下午12:39:23
 */
public class SimpleClient {
    private static HttpParams httpParams;
    private static DefaultHttpClient httpClient;
    private static String JSESSIONID; //定义一个静态的字段，保存sessionID

    /**
     * @return
     * @throws Exception HttpClient               返回
     * @Title: getHttpClient
     * @author 杨贵松
     * @date 2014-3-18 下午1:11:18
     * @Description: 获取HttpClient
     */
    public static HttpClient getHttpClient() throws Exception {
        // 创建 HttpParams 以用来设置 HTTP 参数（这一部分不是必需的）
        httpParams = new BasicHttpParams();
        // 设置连接超时和 Socket 超时，以及 Socket 缓存大小
        HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);
        HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);
        HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
        // 设置重定向，缺省为 true
        HttpClientParams.setRedirecting(httpParams, true);
        // 设置 user agent
        String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6";
        HttpProtocolParams.setUserAgent(httpParams, userAgent);
        // 创建一个 HttpClient 实例
        // 注意 HttpClient httpClient = new HttpClient(); 是Commons HttpClient
        // 中的用法，在 Android 1.5 中我们需要使用 Apache 的缺省实现 DefaultHttpClient
        httpClient = new DefaultHttpClient(httpParams);
        return httpClient;
    }

    /**
     * @param url
     * @param params
     * @return
     * @throws Exception String               返回
     * @Title: doGet
     * @author 杨贵松
     * @date 2014-3-18 下午12:39:58
     * @Description: doGet请求
     */
    @SuppressWarnings("rawtypes")
    public static String doGet(String url, Map params) throws Exception {
        /* 建立HTTPGet对象 */
        String paramStr = "";
        if (params != null) {
            Iterator iter = params.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                Object key = entry.getKey();
                Object val = entry.getValue();
                paramStr += paramStr = "&" + key + "=" + val;
            }
        }
        if (!paramStr.equals("")) {
            paramStr = paramStr.replaceFirst("&", "?");
            url += paramStr;
        }
        HttpGet httpRequest = new HttpGet(url);
        String strResult = "doGetError";
        /* 发送请求并等待响应 */
        HttpResponse httpResponse = httpClient.execute(httpRequest);
        /* 若状态码为200 ok */
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            /* 读返回数据 */
            strResult = EntityUtils.toString(httpResponse.getEntity());
        } else {
            strResult = "Error Response: " + httpResponse.getStatusLine().toString();
        }
        Log.v("strResult", strResult);
        return strResult;
    }

    /**
     * @param url
     * @param params
     * @return
     * @throws Exception String               返回
     * @Title: doPost
     * @author 杨贵松
     * @date 2014-3-18 下午12:39:38
     * @Description: doPost请求
     */
    public static HttpEntity doPost(String url, List<NameValuePair> params) throws Exception {
        /* 建立HTTPPost对象 */
        HttpPost httpRequest = new HttpPost(url);
        String strResult = "doPostError";
        /* 添加请求参数到请求对象 */
        if (params != null && params.size() > 0) {
            httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        }
        if (null != JSESSIONID) {
            httpRequest.setHeader("Cookie", "JSESSIONID=" + JSESSIONID);
        }
        /* 发送请求并等待响应 */
        HttpResponse httpResponse = httpClient.execute(httpRequest);
        /* 若状态码为200 ok */
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            /* 读返回数据 */
            strResult = EntityUtils.toString(httpResponse.getEntity());
            /* 获取cookieStore */
            CookieStore cookieStore = httpClient.getCookieStore();
            List<Cookie> cookies = cookieStore.getCookies();
            for (int i = 0; i < cookies.size(); i++) {
                if ("JSESSIONID".equals(cookies.get(i).getName())) {
                    JSESSIONID = cookies.get(i).getValue();
                    break;
                }
            }
        }
        Log.v("strResult", strResult);
        return httpResponse.getEntity();
    }

    static String cookieval;

    /**
     * 从指定URL获取图片
     *
     * @param url
     * @return
     */
    public static Bitmap getImageBitmap(String url) {
        URL imgUrl = null;
        Bitmap bitmap = null;
        try {
            imgUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imgUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            cookieval = conn.getHeaderField("set-cookie");
            String sessionid = null;
            if (cookieval != null) {
                sessionid = cookieval.substring(0, cookieval.indexOf(";"));
            }
            /*if (sessionid != null) {
                conn.setRequestProperty("cookie", sessionid);
            }*/
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 获取指定URL的响应字符串
     *
     * @param urlString
     * @return
     */
    public static String getURLResponse(String urlString) {
        HttpURLConnection conn = null; //连接对象
        InputStream is = null;
        String resultData = "";
        try {
            URL url = new URL(urlString); //URL对象
            conn = (HttpURLConnection) url.openConnection(); //使用URL打开一个链接
            conn.setDoInput(true); //允许输入流，即允许下载
            conn.setDoOutput(true); //允许输出流，即允许上传
            conn.setUseCaches(false); //不使用缓冲
            conn.setRequestMethod("GET"); //使用get请求
            if (!TextUtils.isEmpty(cookieval)) {
                conn.addRequestProperty("Cookie", cookieval);
            }

            is = conn.getInputStream();   //获取输入流，此时才真正建立链接
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader bufferReader = new BufferedReader(isr);
            String inputLine = "";
            while ((inputLine = bufferReader.readLine()) != null) {
                resultData += inputLine + "\n";
            }

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }

        Log.i("resultData", resultData);
        return resultData;
    }


}